package com.hcx.reggie.exception;
import com.hcx.reggie.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})//拦截加上了对应注解的handler
public class GlobalExceptionHandler{


    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException integrityConstraintViolationException){
        log.error(integrityConstraintViolationException.getMessage());
        if(integrityConstraintViolationException.getMessage().contains("Duplicate entry")){
            String[] chars = integrityConstraintViolationException.getMessage().split(" ");
            return R.error(chars[2] + "已存在T^T");
        }
       return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> CustomExceptionHandler(CustomException customException){
        log.error(customException.getMessage());
        return R.error(customException.getMessage());
    }




}
